package com.eling.elcms.travel.service.impl;

import com.eling.elcms.core.exception.BusinessException;
import com.eling.elcms.core.service.impl.GenericManagerImpl;
import com.eling.elcms.core.util.PropertyUtils;
import com.eling.elcms.travel.dao.IProductTypeDao;
import com.eling.elcms.travel.model.ProductRuleDetail;
import com.eling.elcms.travel.model.ProductType;
import com.eling.elcms.travel.service.IProductRuleDetailManager;
import com.eling.elcms.travel.service.IProductTypeManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ProductTypeManagerImpl extends GenericManagerImpl<ProductType, Long> implements IProductTypeManager{

	IProductTypeDao typeDao;
	
	@Autowired
	private IProductRuleDetailManager detailManager;

	@Autowired
	public void setTypeDao(IProductTypeDao typeDao) {
		this.dao = typeDao;
		this.typeDao = typeDao;
	}

	@Override
	public ProductType changeseal(ProductType productType) {
		List<ProductType> list = this.query(productType);
		productType = list.get(0);
		Boolean seal = productType.getSeal();
		if(seal == true){
			seal = false;
		}else{
			seal = true;
		}
		productType.setSeal(seal);
		productType = this.save(productType);
		return productType;
	}

	@Override
	public ProductType savetype(ProductType productType) {
		//名称唯一性判断
		ProductType all = new ProductType();
		List<ProductType> list = this.query(all);
		for (ProductType prodtype : list) {
			if(prodtype.getName().equals(productType.getName())){
				if(!prodtype.getPkProductType().equals(productType.getPkProductType())){
					throw new BusinessException("名称不能重复");
				}
			}
		}
		return this.save(productType);
	}

	@Override
	public boolean seekquote(Long pkProductType) {
		ProductRuleDetail detail = new ProductRuleDetail();
		List<ProductRuleDetail> list = detailManager.query(detail);
		boolean flag = false;
		for (ProductRuleDetail productDetail : list) {
			if(productDetail.getProductType() != null){
				if(productDetail.getProductType().getPkProductType().equals(pkProductType)){
					flag = true;
					break;
				}
			}
		}
		return flag;
	}

	@Override
	public List<ProductType> queryType(Long pkProduct) {
		ProductRuleDetail detail = new ProductRuleDetail();
		PropertyUtils.setProperty(detail, "product.pkProduct", pkProduct);
		List<ProductRuleDetail> list = detailManager.query(detail);
		List<ProductType> proTypeList = new ArrayList<ProductType>();
		if(!list.isEmpty()){
			proTypeList = list.stream().map(a->a.getProductType()).collect(Collectors.toList());
		}
		return proTypeList;
	}
}
